package io.renren.core.config;


import io.renren.core.interceptor.AuthorizationInterceptor;
import io.renren.core.interceptor.OuterInterfaceAuthorizationInterceptor;
import io.renren.core.resolver.LoginUserHandlerMethodArgumentResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

/**
 * @Author: hongyuliu
 * @Date: 2019/2/19
 * @Version 1.0
 */

@Component
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Autowired
    private AuthorizationInterceptor authorizationInterceptor;

    @Autowired
    private OuterInterfaceAuthorizationInterceptor outerInterfaceAuthorizationInterceptor;


    @Autowired
    private LoginUserHandlerMethodArgumentResolver loginUserHandlerMethodArgumentResolver;

    /**
     * 添加权限拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        // 权限拦截器
        registry.addInterceptor(authorizationInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/actuator/**",
                        "/api/wechat/**",
                        "/mini/project/**"
                )
                .excludePathPatterns("/outer/**");

        // 外部接口拦截器
        registry.addInterceptor(outerInterfaceAuthorizationInterceptor)
                .addPathPatterns("/outer/**");
    }

    /**
     * 解决跨域问题
     *
     * @param registry
     */
    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedHeaders("*")
                .allowedMethods("GET, POST, PUT, DELETE, OPTIONS")
                .maxAge(3600);

        super.addCorsMappings(registry);
    }

    @Override
    protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(loginUserHandlerMethodArgumentResolver);
    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/public/**")
                .addResourceLocations("classpath:/static/public/");
    }
}
